package main

import (
	"container/list"
)

type iocb func(l *Loop, events uint32)

type io struct {
	pendingLink *list.Element
	watcherLink *list.Element
	pevents     uint32
	cevents     uint32
	fd          int
	cb          iocb
}

func (this *io) init(cb iocb, fd int) {
	this.pendingLink = nil
	this.watcherLink = nil
	this.pevents = 0
	this.cevents = 0
	this.cb = cb
	this.fd = fd
}

func (this *io) start(l *Loop, events uint32) {
	this.pevents |= events
	if this.cevents == this.pevents {
		return
	}
	if this.watcherLink == nil {
		this.watcherLink = l.watcherQueue.PushBack(this)
	}
	if l.watchers[this.fd] == nil {
		l.watchers[this.fd] = this
	}
}

func (this *io) stop(l *Loop, events uint32) {
	if this.fd == -1 {
		return
	}
	this.pevents &= ^events
	if this.pevents == 0 {
		l.watcherQueue.Remove(this.watcherLink)
		this.watcherLink = nil
		if l.watchers[this.fd] != nil {
			delete(l.watchers, this.fd)
			this.cevents = 0
		}
	} else if this.watcherLink == nil {
		this.watcherLink = l.watcherQueue.PushBack(this)
	}
}

func (this *io) active(events uint32) bool {
	return ((this.pevents & events) != 0)
}
